package com.traffic.between.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class ConfigurableConstants {
	protected static Logger logger = Logger.getLogger(ConfigurableConstants.class);

	protected static Properties p = new Properties();

	public static void init(String propertyFileName) {
		InputStream in = null;
		try {
			File file = findTomcatConfFile(propertyFileName);
			if (file != null)
				in = new FileInputStream(file);
			else {
				in = ConfigurableConstants.class.getClassLoader().getResourceAsStream(propertyFileName);
			}
			if (in != null)
				p.load(in);
		} catch (IOException e) {
			logger.error("load " + propertyFileName + " into Constants error!");
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					logger.error("close " + propertyFileName + " error!");
				}
		}
	}

	public static String getProperty(String key, String defaultValue) {
		return p.getProperty(key, defaultValue);
	}

	public static File findTomcatConfFile(String fileName) {
		String homePath = System.getProperty("catalina.home");
		if (StringUtils.isNotBlank(homePath)) {
			homePath = homePath + File.separator + "conf" + File.separator + fileName;
			logger.info("between -findTomcatConfFile()tomcatPath=" + homePath);
			File file = new File(homePath);
			if (file.exists()) {
				return file;
			}
		}
		return null;
	}
}